package training.bms.business;

import java.util.Date;

import org.apache.commons.lang.ObjectUtils;

import training.bms.persistence.BlogDao;
import training.framework.business.AbstractEntityController;
import training.framework.business.BusinessException;
import training.framework.persistence.AbstractEntityDao;

public class BlogController extends AbstractEntityController<Integer, Blog, BlogSearchOptions>{
	private BlogDao dao;
	
	BlogController(BlogDao dao) {
		this.dao = dao;
	}
	
	public BlogController() {
		dao = new BlogDao();
	}
	/*
	public void saveBlog(Blog blog) {
		String blogName = blog.getName();
		Blog databaseBlog = dao.selectBlog(blogName);
		if (databaseBlog == null) {
			if (blog.getIdentifier() == null) {
				blog.setCreationDate(new Date());
				dao.insertEntity(blog);				
			} else {
				dao.updateEntity(blog);
			}
		} else {
			if (ObjectUtils.equals(blog.getIdentifier(), databaseBlog.getIdentifier())) {
				dao.updateEntity(blog);
			} else {
				throw new BusinessException("There is already a blog named " + blogName);
			}
		}
	}
	

	public int searchBlogCount(BlogSearchOptions options) {
		return dao.selectEntityCount(options);
	}
	
	public List<Blog> searchBlog(BlogSearchOptions options) {
		return dao.selectEntity(options);
	}

	public void deleteBlog(Blog blog) {
		dao.deleteEntity(blog);
	}*/

	@Override
	protected AbstractEntityDao<Integer, Blog, BlogSearchOptions> getDao() {
		return this.dao;
	}

	@Override
	protected void validateUpdate(Blog entity) {
		validateEntity(entity);
		String blogName = entity.getName();
		Blog databaseBlog = dao.selectBlog(blogName);
		if (databaseBlog != null){
			if(!ObjectUtils.equals(entity.getIdentifier(), databaseBlog.getIdentifier())){
				throw new BusinessException("There is already a blog named: "+blogName);
			}			
		}
		
	}

	private void validateEntity(Blog entity) {
		if (entity == null){
			throw new IllegalArgumentException("entity == null");
		}
	}

	@Override
	protected void validadeInsert(Blog entity) {
		validateEntity(entity);
		if (entity.getIdentifier() != null){
			throw new IllegalArgumentException("entity.getIdentifier() != null");
		}
		validateUpdate(entity);
		entity.setCreationDate(new Date());
		
	}

	@Override
	public void validateDelete(Blog entity) {
		// TODO Auto-generated method stub
		
	}
}
